package cn.stylefeng.guns.sys.modular.system.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.listener.HykzsExcelListener;
import cn.stylefeng.guns.sys.core.util.JsonResult;
import cn.stylefeng.guns.sys.modular.system.entity.BtyHykzs;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyHykzsMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyHykzsParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyHykzsResult;
import cn.stylefeng.guns.sys.modular.system.service.BtyHykzsService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;


/**
 * 控制器
 *
 * @author liuy
 * @Date 2022-05-04 10:40:48
 */
@Controller
@RequestMapping("/btyHykzs")
public class BtyHykzsController extends BaseController {

    private String PREFIX = "/modular/system/btyHykzs";

    @Autowired
    private BtyHykzsService btyHykzsService;
    @Resource
    private BtyHykzsMapper hykzsMapper;

    /**
     * 跳转到主页面
     *
     * @author liuy
     * @Date 2022-05-04
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/btyHykzs.html";
    }

    /**
     * 新增页面
     *
     * @author liuy
     * @Date 2022-05-04
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/btyHykzs_add.html";
    }

    /**
     * 编辑页面
     *
     * @author liuy
     * @Date 2022-05-04
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/btyHykzs_edit.html";
    }

    /**
     * 新增接口
     *
     * @author liuy
     * @Date 2022-05-04
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(BtyHykzsParam btyHykzsParam) {
        this.btyHykzsService.add(btyHykzsParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author liuy
     * @Date 2022-05-04
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(BtyHykzsParam btyHykzsParam) {
        this.btyHykzsService.update(btyHykzsParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author liuy
     * @Date 2022-05-04
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(BtyHykzsParam btyHykzsParam) {
        this.btyHykzsService.delete(btyHykzsParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author liuy
     * @Date 2022-05-04
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(BtyHykzsParam btyHykzsParam) {
        BtyHykzs detail = this.btyHykzsService.getById(btyHykzsParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author liuy
     * @Date 2022-05-04
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(BtyHykzsParam btyHykzsParam) {
        return this.btyHykzsService.findPageBySpec(btyHykzsParam);
    }

    /**
     * 导入excel
     *  Boolean result;
     *         try {
     *             result = this.pzxqService.batchImportPzxq(fileName, file,dm);
     *         } catch (Exception e) {
     *             e.printStackTrace();
     *             jsonResult.setState(0);
     *             jsonResult.setErrmsg(e.getMessage());
     *             return jsonResult;
     *         }
     *         return result;
     */
    @RequestMapping("/import")
    @ResponseBody
    public Object imports(@RequestParam("file") MultipartFile file, BtyHykzsParam hykzsParam) {
        JsonResult jsonResult = new JsonResult();
        if(ToolUtil.isEmpty(hykzsParam.getZdrq())){
            jsonResult.setState(0);
            jsonResult.setErrmsg("请先选择制单日期！");
            return jsonResult;
        }
        //导入之前删掉之前的数据
        hykzsMapper.delete(new QueryWrapper<>());
        try {
            HykzsExcelListener basicExcelListener = new HykzsExcelListener(btyHykzsService);
            EasyExcel.read(file.getInputStream(), BtyHykzs.class, basicExcelListener).sheet(0).doRead();
            //导入成功之后按大区生成凭证
            String zdrq=hykzsParam.getZdrq();
            List<BtyHykzsResult>list=hykzsMapper.hykzsList();
            for (BtyHykzsResult mtResult : list) {
                BigDecimal zsje=mtResult.getZsje();
                String bh=mtResult.getRegion();
                String yaoma=mtResult.getYaoma();
                String dm=mtResult.getDm();
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("trantype", "code"); // 档案翻译方式，枚举值为：编码请录入 code， 名称请录入 name， 主键请录入 pk
                headers.add("system", "001"); // 系统编码
                headers.add("usercode", "15253172037"); // 用户
                headers.add("password", "514576f58a89767b46c1b44767a08f77");
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());

                StringBuilder sb=new StringBuilder();
                sb.append("{\n" +
                        "    \"voucher\":[\n" +
                        "        {\n" +
                        "            \"details\":[");

                //天财会员卡赠送凭证
                sb.append("                {\n" +
                        "                    \"ass\":[\n" +
                        "                        {\n" +
                        "                            \"checktypecode\":\"2\",\n" +
                        "                            \"checkvaluecode\":'"+yaoma+"'\n" +
                        "                        }\n" +
                        "                    ],\n" +
                        "                    \"creditamount\":\"\",\n" +
                        "                    \"debitamount\":\""+zsje+"\",\n" +
                        "                    \"explanation\":\"老系统会员卡赠送金额\",\n" +
                        "                    \"localcreditamount\":\"\",\n" +
                        "                    \"localdebitamount\":\"\",\n" +
                        "                    \"pk_accsubj\":\"660121\",\n" +
                        "                    \"pk_currtype\":\"CNY\"\n" +
                        "                }," +
                        "{\n" +
                        "\t\t\t\t\"ass\":[\n" +
                        "                        {\n" +
                        "                            \"checktypecode\":\"2\",\n" +
                        "                            \"checkvaluecode\":'"+yaoma+"'\n" +
                        "                        },\n" +
                        "\t\t\t\t\t\t{\n" +
                        "                            \"checktypecode\":\"7\",\n" +
                        "                            \"checkvaluecode\":\"0022\"\n" +//会员卡(储值)辅助核算编码
                        "                        }\n" +
                        "                    ],\n" +
                        "                    \"creditamount\":\""+zsje+"\",\n" +
                        "                    \"creditquantity\":\"\",\n" +
                        "                    \"debitamount\":\"\",\n" +
                        "                    \"debitquantity\":\"\",\n" +
                        "                    \"detailindex\":\"\",\n" +
                        "                    \"excrate1\":\"\",\n" +
                        "                    \"explanation\":\"老系统会员卡赠送金额\",\n" +
                        "                    \"localcreditamount\":\"\",\n" +
                        "                    \"localdebitamount\":\"\",\n" +
                        "                    \"pk_accsubj\":\"112210\",\n" +
                        "                    \"pk_currtype\":\"CNY\",\n" +
                        "                    \"price\":\"\"\n" +
                        "                },\n");
                sb.append("            ],\n" +
                        "            \"pk_corp\":"+bh+",\n" +
                        "            \"pk_glorgbook\":\""+bh+"-bty01\",\n" +
                        "            \"pk_prepared\":\"15253172037\",\n" +
                        "            \"pk_vouchertype\":\"记账\",\n" +
                        "            \"prepareddate\":\""+zdrq+"\"\n" +
                        "        }\n" +
                        "    ]\n" +
                        "}");
                //System.out.println("sb:"+sb.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(sb.toString(), headers);
                String url = "http://124.70.28.147:8089/u8cloud/api/gl/voucher/insert";
                String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
                System.out.println("result:"+result);
                JsonParser jp = new JsonParser();
                //将json字符串转化成json对象
                JsonObject jo = jp.parse(result).getAsJsonObject();
                //获取status对应的值
                String status = jo.get("status").getAsString();

                if(status.equals("falied")){
                    String errormsg = jo.get("errormsg").getAsString();
                    BtyHykzs hykzs=btyHykzsService.getOne(new QueryWrapper<BtyHykzs>().eq("dm",dm));
                    if(ToolUtil.isNotEmpty(hykzs)){
                        hykzs.setErrormsg(errormsg);
                        btyHykzsService.updateById(hykzs);
                    }
                    //List<BtyMtsxf>list1=mtsxfMapper.selectList(new QueryWrapper<BtyMtsxf>().eq("mdid",mdid));
//                    if(list1.size()>0){
//                        BtyMtsxfParam param1=new BtyMtsxfParam();
//                        param1.setMdid(mdid);
//                        param1.setErrormsg(errormsg);
//                        mtsxfMapper.updateErrorMsgByMdid(param1);
//                    }
                    //
                    //System.out.println("errormsg:"+errormsg);
                }else{
                    BtyHykzs hykzs=btyHykzsService.getOne(new QueryWrapper<BtyHykzs>().eq("dm",dm));
                    if(ToolUtil.isNotEmpty(hykzs)){
                        hykzs.setFlag(1);
                        btyHykzsService.updateById(hykzs);
                    }
//                    List<BtyMtsxf>list1=mtsxfMapper.selectList(new QueryWrapper<BtyMtsxf>().eq("mdid",mdid));
//                    if(list1.size()>0){
//                        BtyMtsxfParam param1=new BtyMtsxfParam();
//                        param1.setMdid(mdid);
//                        mtsxfMapper.updateByMdid(param1);
//                    }
                    System.out.println("凭证生成成功！");
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            jsonResult.setState(0);
            jsonResult.setErrmsg(e.getMessage());
            return jsonResult;
        }
        return true;
    }

}


